package com.ulook.lookplanet.widget;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;

import com.qmuiteam.qmui.widget.QMUIProgressBar;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.ulook.lookplanet.R;



/**
 * 描述：音频播放器组件
 *
 * @author L1998
 * @data 2021/4/10
 */
public class AudioPlayerLayout extends LinearLayout {

    private Context context;

    private QMUIRadiusImageView2 imageView;
    private QMUIProgressBar progressBar;
    private MediaPlayer mediaPlayer;
    private String mediaPath;
    //运用Handler中的handleMessage方法接收子线程传递的信息
    private Handler handler;
    private AudioThread audioThread;
    private boolean isPlaying;

    public AudioPlayerLayout(Context context) {
        super(context);
        initAudioPlayerLayout(context);
    }

    public AudioPlayerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAudioPlayerLayout(context);
    }

    public AudioPlayerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAudioPlayerLayout(context);
    }

    /**
     * 初始化组件
     */
    private void initAudioPlayerLayout(Context context){
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.widget_audio_player, this, true);

        imageView = findViewById(R.id.audio_player_bt);
        imageView.setOnClickListener(view -> {
            if(mediaPlayer != null){
                if(isPlaying){
                    stop();
                }else {
                    play();
                }
            }else {
                play();
            }
        });
        progressBar = findViewById(R.id.audio_player_progress);
    }

    public QMUIRadiusImageView2 getImageView() {
        return imageView;
    }

    public QMUIProgressBar getProgressBar() {
        return progressBar;
    }

    /**
     * 设置播放资源路径
     * @param mediaPath 音频文件路径
     */
    public void setMediaPath(String mediaPath){
        this.mediaPath = mediaPath;

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                progressBar.setProgress(msg.what);
            }
        };
        audioThread = new AudioThread();
    }

    public MediaPlayer getMediaPlayer(){
        return mediaPlayer;
    }

    /**
     * 创建资源，并播放
     */
    public void play(){
        if(mediaPath != null){
            if(mediaPlayer != null){
                mediaPlayer.release();
            }
            mediaPlayer = MediaPlayer.create(context, Uri.parse(mediaPath));
            progressBar.setMaxValue(mediaPlayer.getDuration());
            progressBar.setProgress(0);
            mediaPlayer.setOnCompletionListener(player -> {
                progressBar.setProgress(mediaPlayer.getDuration());
                stop();
            });
            mediaPlayer.setOnErrorListener((player, i, i1) -> {
                stop();
                return false;
            });
            mediaPlayer.start();
            audioThread.start();
            isPlaying = true;
            imageView.setBackground(context.getDrawable(R.drawable.ic_audio_stop));
        }

    }

    /**
     * 停止，并释放资源
     */
    public void stop(){
        if(mediaPlayer != null){
            audioThread.interrupt();
            isPlaying = false;
            mediaPlayer.stop();
            mediaPlayer.release();
            imageView.setBackground(context.getDrawable(R.drawable.ic_audio_play));
        }
    }

    //建立一个子线程实现Runnable接口
    private class AudioThread extends Thread {
        @Override
        public void run() {
            //判断音乐的状态，在不停止与不暂停的情况下向总线程发出信息
            while (mediaPlayer != null && isPlaying) {
                //发出的信息
                handler.sendEmptyMessage(mediaPlayer.getCurrentPosition());
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }


}
